<!--
 * @Author: zhangjingyu
 * @Date: 2020-12-03 11:23:08
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-05-19 10:23:09
 * @FilePath: \vprisk10.14\src\components\webSocket\WebSocket.vue
 * @Description: webSocket实时消息推送
-->
<template>
  <div></div>
</template>

<script>
import { systemManage } from "@/api/index";
export default {
  name:"webSocket",
  data() {
    return {
        socket:null,
        userInfo:null,
        count:1
    };
  },
  created() {
    //绑定事件
    window.addEventListener('beforeunload',e=>this.closeSocket(e))
    this.getUserId();
  },
  beforeDestroy () {
      //卸载事件
    window.removeEventListener('beforeunload',e=>this.closeSocket(e))
  },      
  methods: {
    getUserId(){
      systemManage.getCurrentUserInfo().then(res=>{
        if(res.code==200){
          this.userInfo = res.data;
       // 连接webSocket，用于接收后台实时信息推送
        setTimeout(()=>{
           this.webSocket();
        },1000)

        }else{
          this.$notify({
          title: '提示',
          message: '获取用户信息失败，无法开启实时消息推送。',
          type: 'warning',
          duration: 5000
        });
        }
      })
    },
    closeSocket(e){
      if(this.socket){
        this.socket.close()
      }
    },
    webSocket() {
      const that = this;
      if (typeof (WebSocket) == 'undefined') {
        this.$notify({
          title: '提示',
          message: '当前浏览器不支持接收实时信息，请使用谷歌浏览器！',
          type: 'warning',
          duration: 0
        });
      } else {
          // 实例化socket，这里我把用户名传给了后台，使后台能判断要把消息发给哪个用户，其实也可以后台直接获取用户IP来判断并推送
          // const socketUrl = 'ws//:'+baseurl.replace('http:','')+'webSocketServer/'+this.userInfo.userId;
          const socketUrl = systemManage.messageSokect().replace('http','ws').replace('https','ws')+this.userInfo.userId;
          // const socketUrl = systemManage.messageSokect().replace('http','ws').replace('https','ws')+'123456'+'?access_token='+sessionStorage.getItem('loginToken');
            console.log('浏览器WebSocket已打开,路径：',socketUrl);
          this.socket = new WebSocket(socketUrl);
          console.log(this.socket)
          // 监听socket打开
          this.socket.onopen = function() {
            // this.socket.send({})
            console.log('浏览器WebSocket已打开',socketUrl);
          };
          // 监听socket消息接收
          this.socket.onmessage = function(msg) {
            // 转换为json对象
            // let data = msg.data.match(/\[(\S*)\]/)[1];
            console.log(msg)
            const data =  JSON.parse(msg.data) ;
            if(data){that.count = data.count; that.$store.commit('setCount',that.count*1)}
            console.log("实时消息", data)
            if(data.withoutmsg&&data.withoutmsg=='1'){
              that.$notify({
                title: '消息系统连接成功',
                message: '点击进入消息通知',
                type: 'success',
                duration: 5000,
                onClick: () => {
                   that.$router.push({ name: 'message'});
                   that.$store.commit('toMessagePage')
                }
              })
            }else{
              that.$notify({
                title: '新消息',
                // 这里也可以把返回信息加入到message中显示
                message: '主题：'+data.title+'(点击查看消息详情)',
                type: 'success',
                duration: 5000,
                onClick: () => {
                   that.$router.push({ name: 'message'});
                   that.$store.commit('toMessagePage')
                }
              })
            }
            
          };
          // 监听socket错误
          this.socket.onerror = function(err) {
            console.log('WebSocket错误',err);
            that.$notify({
              title: '错误',
              message: '服务器错误，无法实时接收推送信息',
              type: 'error',
              duration: 3000
            });
          };
          // 监听socket关闭
          this.socket.onclose = function() {
            console.log('WebSocket已关闭');
          }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
</style>